<?php

/**
 * @author LSH 2013-03-19 
 *  新浪授权页 ..
 *  关于新浪的操作必须经过新浪授权之后才能进行..
 */
class TSina extends MY_Controller{
	
	public $m_openID  = 0;
	public $m_token   = null;
	public $m_outTime = null;

	
	
	// 新浪微博平台编号 ..
	public static $m_platformId = T_SINA_TYPE;
	
	
	public $m_callback = '';
	
	public function __construct()
	{
		parent::__construct();
		$this->load->config('oauth2');
		
		// 生成一个新浪Oauth类实例
		$config = $this->config->item('oauht2');
		$appConfig = $config['t_sina'];
		
		$this->m_callback = $appConfig['t_callback_url'];
		
		$this->load->library('Sina/MY_SinaOauth',$appConfig);
			
		// 载入session
		$this->load->library('session');
		
		// 载入model
		$this->load->model('account/account_m');
	}
	public function index()
	{
		
		// 如果没有authorizeCode，跳转到用户授权页面
		if ( ! isset($_GET['code'])) {
			$authorizeUrl = $this->my_sinaoauth->getAuthorizeURL($this->m_callback);
			
			header('Location:' . $authorizeUrl);
			exit;
		}
	
		
	}
	
	public function callback()
	{
		// 设置authorizeCode
		$code = $this->input->get('code');
		
		$para = array(
				'code' => $code,
				'redirect_uri' => $this->m_callback,
				);
		
		// 通过authorizeCode获取accessToken，至此完成用户授权
		$arrTSina = $this->my_sinaoauth->getAccessToken('code',$para);
		
		// 授权成功
		if (is_array($arrTSina) || isset($arrTSina['access_token']))
		{
			$this->m_openID   = $arrTSina['uid'];
			$this->m_token    = $arrTSina['access_token'];
			$this->m_outTime  = $arrTSina['expires_in'];
			
			// 写入session 中
				
			$newSession = array(
					'openID' => $this->m_openID,
					'token'  => $this->m_token,
					'outTime'=> date('Y-m-d H:i:s',time() + (int)$this->m_outTime),
			);
			$this->session->set_userdata(array(SESSION_TSINA => $newSession));
			
			
			// 判断是否已经绑定 ...
			
			$filter = array(
					'openID' => $this->m_openID,
					'platformID' => self::$m_platformId,
					);
			$acc2platList = $this->account_m->getPlatfromList($filter);
			
			$this->oauth2($acc2platList);
		}
		
		
	}
}